package psi.springapp.mvc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateExceptionTranslator;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;


/**
 * Created with IDEA.
 * Voter: Ѱ
 * Date: 28.09.14
 * Time: 10:36
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "psi.springapp.mvc.repositories")

public class JPAConfiguration {
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dm = new DriverManagerDataSource();
        dm.setDriverClassName("com.mysql.jdbc.Driver");
        dm.setUrl("jdbc:mysql://localhost:3306/party");
        dm.setUsername("root");
        dm.setPassword("root123");
        return dm;
    }

    @Bean

    public EntityManagerFactory entityManagerFactory() {
        HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
        hibernateJpaVendorAdapter.setGenerateDdl(true);
        LocalContainerEntityManagerFactoryBean managerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        managerFactoryBean.setJpaVendorAdapter(hibernateJpaVendorAdapter);
        managerFactoryBean.setPackagesToScan("model");
        managerFactoryBean.setDataSource(dataSource());
        managerFactoryBean.afterPropertiesSet();
        return managerFactoryBean.getObject();
    }

    @Bean
    public EntityManager entityManager(EntityManagerFactory factory){
        return factory.createEntityManager();
    }
    @Bean
    public PlatformTransactionManager transactionManager(){
        JpaTransactionManager jpaTransactionManager = new JpaTransactionManager();
        jpaTransactionManager.setEntityManagerFactory(entityManagerFactory());
        return jpaTransactionManager;
    }

    @Bean
    public HibernateExceptionTranslator exceptionTranslator(){
        return new HibernateExceptionTranslator();
    }
}
